package cn.ctodb.notebook.wxapp.controller;

import cn.ctodb.notebook.wxapp.service.MessageService;
import cn.ctodb.notebook.wxapp.service.PicService;
import cn.ctodb.notebook.wxapp.service.WxUserService;
import cn.ctodb.notebook.wxapp.service.dto.MessageDTO;
import cn.ctodb.notebook.wxapp.service.dto.PicDTO;
import cn.ctodb.notebook.wxapp.service.dto.WxUserDTO;
import cn.ctodb.notebook.wxapp.service.util.HttpUtils;
import cn.ctodb.notebook.wxapp.web.rest.util.PaginationUtil;
import cn.ctodb.notebook.wxapp.web.rest.vm.MsgReq;
import cn.ctodb.notebook.wxapp.web.rest.vm.WxappResp;
import com.codahale.metrics.annotation.Timed;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@RestController()
@RequestMapping("/wxapp")
public class WxappController {

    String appid = "wx9a68d55ef65ca6e0";
    String secret = "356c2a3d6069ed610c8ba3160292f825";
    String jscode2session = "https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=SECRET&js_code=JSCODE&grant_type=authorization_code";

    @Autowired
    private WxUserService wxUserService;
    @Autowired
    private MessageService messageService;
    @Autowired
    private PicService picService;

    @ApiOperation(value = "用户登录获取openid与session")
    @GetMapping("/jscode2session")
    public Object jscode2session(@RequestParam String code) {
        String url = jscode2session.replace("APPID", appid).replaceAll("SECRET", secret).replaceAll("JSCODE", code);
        String re = HttpUtils.get(url);
        return re;
    }

    @ApiOperation(value = "保存用户")
    @PostMapping("/saveUser")
    public WxappResp saveUser(@RequestBody WxUserDTO wxUserDTO) {
        return new WxappResp(wxUserService.save(wxUserDTO));
    }

    @ApiOperation(value = "保存信息")
    @PostMapping("/saveMsg")
    public WxappResp saveMsg(@RequestBody MsgReq msgReq) {
        msgReq.setMessageDTO(messageService.save(msgReq.getMessageDTO()));
        if (msgReq.getPicDTOS() != null) for (PicDTO picDTO : msgReq.getPicDTOS()) {
            picDTO.setMessageId(msgReq.getMessageDTO().getId());
            picService.save(picDTO);
        }
        return new WxappResp(msgReq.getMessageDTO());
    }

    @ApiOperation(value = "文件上传")
    @PostMapping("/upload")
    public WxappResp upload(@RequestParam(name = "file") MultipartFile file)
        throws Exception {
        String dir = "/data/file";
        String path = "/" + new SimpleDateFormat("yyyy/MM/dd").format(new Date()) + "/";
        new File(dir + path).mkdirs();
        String filePath = path + UUID.randomUUID().toString() + "." + getTypeName(file.getOriginalFilename());
        FileCopyUtils.copy(file.getBytes(), new File(dir + filePath));
        return new WxappResp(filePath);
    }

    @ApiOperation(value = "文件下载")
    @GetMapping("/download")
    public ResponseEntity download(@RequestParam(name = "path") String path) throws IOException {
        String dir = "/data/file";
        File file = new File(dir + path);
        HttpHeaders headers = new HttpHeaders();
        headers.setContentDispositionFormData("attachment", new String(file.getName().getBytes("UTF-8"), "iso-8859-1"));
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        return new ResponseEntity(FileCopyUtils.copyToByteArray(file), headers, HttpStatus.OK);
    }

    private String getTypeName(String s) {
        String prefix = s.substring(s.lastIndexOf(".") + 1);
        return prefix;
    }

    @ApiOperation(value = "消息分页")
    @GetMapping("/messages")
    @Timed
    public ResponseEntity<List<MessageDTO>> getAllMessages(Pageable pageable) {
        Page<MessageDTO> page = messageService.findAll(pageable);
        HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(page, "/wxapp/messages");
        return new ResponseEntity<>(page.getContent(), headers, HttpStatus.OK);
    }

}
